﻿#include "testQt.h"
#include <QDebug.h>
#include <QFileDialog>
#include <QDesktopServices>
#include "cloud.hpp"
#include <QtConcurrent/QtConcurrent>

#define BACKUP_FILE "./backup.dat"


testQt::testQt(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::testQtClass())
{
    ui->setupUi(this);

    //ui->files_show->setDragEnabled(true);//支持拖出
    //ui->files_show->setSelectionMode(QAbstractItemView::ExtendedSelection);//支持多选
    ////视图中启用放置
    //ui->files_show->setAcceptDrops(true);
    //ui->files_show->setDropIndicatorShown(true);

    //创建文件系统模型
    fileModel = new QFileSystemModel(this);
    //fileModel->setRootPath(QDir::rootPath());

    //绑定文件模型
    ui->files_show->setModel(fileModel);

    ui->btn_select->setText("select your monitor folder");
    ui->label_file->setText("monitor folder");


    // 设置列宽策略：前三列按内容调整，最后一列拉伸
    ui->files_show->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
    ui->files_show->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
    ui->files_show->header()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
    ui->files_show->header()->setStretchLastSection(true);

    // 模型加载完成后调整列宽
    QObject::connect(fileModel, &QFileSystemModel::directoryLoaded, [&](const QString&) {
        ui->files_show->header()->resizeSections(QHeaderView::ResizeToContents);
    });

}

QString& testQt::GetBacUpDir() {
    return BackUpDir;
}

testQt::~testQt()
{
    delete ui;
}

void monitor(QString BackUpDir) {
    std::string Backup = BackUpDir.toStdString();
    cloud::Backup backup(BackUpDir.toStdString(), BACKUP_FILE);
    backup.RunModule();
}

void testQt::selectFile() {
    QString dir = QFileDialog::getExistingDirectory(
        this,
        "Select your floder",
        QDir::homePath(),
        QFileDialog::ShowDirsOnly
    );
    qDebug() << "select file is :" << dir;
    BackUpDir = dir;
    qDebug() << "BackUpDir is：" << BackUpDir;

    ui->label_show->setText(dir);

    fileModel->setRootPath(dir);
    ui->files_show->setRootIndex(fileModel->index(dir));

    // 启动并发任务
    QFuture<void> future = QtConcurrent::run(monitor, BackUpDir);
}

